package Admin

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/Admin"
	"FromNowOnPromote/博客系统/Tblog/models/Blog"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
)

type BlogManage struct {
	controllers.MainController
}

type BlogManageResp struct {
	BlogId     int
	CreateTime string
	BlogTitle  string
	BlogView   int
}

//获取所有博客文章信息
func (this *BlogManage) SendBlog() {
	//验证管理员
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	AdminId, err1 := rd.Get(uuid)
	if AdminId == "" || err1 != nil {
		body := map[string]interface{}{"code": 300, "data": "验证失败", "msg": "管理员账号不存在"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//查找所有博客文章信息
	db := models.ConnDb()
	defer db.Close()
	var bmr []BlogManageResp
	var tl Blog.TBloginfo
	err2 := db.Model(&tl).Where("is_deleted =0").Order("blog_view DESC").Scan(&bmr).Error
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}

	body := map[string]interface{}{"code": 200, "data": bmr, "msg": "查询成功"}
	this.Data["json"] = body
	this.ServeJSON()
	return
}

type BlogManagePostResp struct {
	BlogId int `json:"BlogId"`
}

type BlogData struct {
	BlogTitle   string
	BlogViewUrl string
}

func (this *BlogManage) SendRedis() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	AdminId, err1 := rd.Get(uuid)
	if AdminId == "" || err1 != nil {
		body := map[string]interface{}{"code": 300, "data": "验证失败", "msg": "管理员账号不存在"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	var bmpr BlogManagePostResp
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	err2 := decoder.Decode(&bmpr)
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	var tb Blog.TBloginfo
	var bd BlogData
	db := models.ConnDb()
	defer db.Close()
	//err3:=db.Raw("select * from tbloginfo where blog_id=? and is_deleted=0",bmpr.BlogId).Scan(&bd).Error
	err3 := db.Model(&tb).Where("blog_id = ? ", bmpr.BlogId).Scan(&bd).Error
	if err3 != nil {
		body := map[string]interface{}{"code": 302, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//推送数据存数据库
	ts := Admin.TBlogTuiSong{BlogTitle: bd.BlogTitle, BlogViewUrl: bd.BlogViewUrl}
	err3 = db.Create(&ts).Error
	if err3 != nil {
		body := map[string]interface{}{"code": 303, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "msg": "请求成功"}
	this.Data["json"] = body
	this.ServeJSON()
	return
}
